package com.theyeasy.dvmini.socket;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.theyeasy.dvmini.model.WebSockMsg;

/**
 * 消息发送队列
 * 
 * @author Administrator
 */
public class QueueMessage extends Thread {

	private static Logger log = LoggerFactory.getLogger(QueueMessage.class);
	private final static Queue<WebSockMsg> queue;

	static {
		queue = new LinkedList<WebSockMsg>();
	}

	public static void offerMessage(WebSockMsg msg) {
		queue.offer(msg);
		TextMessage message = new TextMessage(msg.toJson());
		try {
			if (!msg.isReaded()) {
				if (msg.getSalesid() == 0 || msg.getAskfrom() == 2) {
					PcWebSocketHandler.sendMessageToRandomVankor(message, 3);
				} else {
					PcWebSocketHandler.sendToOne(message, "1", msg.getSalesid());
					PcWebSocketHandler.sendToOne(message, "0", msg.getSalesid());
				}

			} else {
				log.info("【互动游戏】发送消息给{}{}", msg.isReaded() ? "粉丝" : "销售",
						msg.isReaded() ? msg.getFansid() : msg.getSalesid());
				PcWebSocketHandler.sendToOne(message, "1", msg.isReaded() ? msg.getFansid() : msg.getSalesid());

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void run() {
		int i = 0;
		int inx = 0;
		while (true) {
			i++;
			if (i == 10000) {
				try {
					Thread.sleep(1000);
					i = 0;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			Map<String, Map<Integer, WebSocketSession>> usermap = PcWebSocketHandler.getUsermap();
			WebSockMsg msg = null;
			TextMessage textMessage = null;
			try {

				while ((msg = queue.poll()) != null) {
					inx = 0;
					Map<Integer, WebSocketSession> map = null;
					if (msg.getAskfrom() == 2) {
						map = usermap.get("0");
					} else {
						map = usermap.get("1");
					}
					if (map != null && map.size() != 0) {

						map.forEach((k, v) -> {
							if (v.isOpen()) {
								try {
									v.sendMessage(textMessage);
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						});

					}

					if (inx <= 0) {
						queue.offer(msg);
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
